package ru.arriah.servicedesk.web.leadExecutor;

import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.Collection;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import ru.arriah.common.bean.MessageBean;
import ru.arriah.common.web.UIController;
import ru.arriah.common.web.action.ActionMapping;
import ru.arriah.servicedesk.bean.EmployeeBean;
import ru.arriah.servicedesk.bean.IntWrapper;
import ru.arriah.servicedesk.bean.RequestBean;
import ru.arriah.servicedesk.bean.TaskBean;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalHome;
import ru.arriah.servicedesk.ejb.EmployeeManagerLocalObject;
import ru.arriah.servicedesk.ejb.RequestManagerLocalHome;
import ru.arriah.servicedesk.ejb.RequestManagerLocalObject;
import ru.arriah.servicedesk.help.Utils;
import ru.arriah.servicedesk.web.commonaction.exception.LoginException;
import ru.arriah.servicedesk.web.leadExecutor.action.Action;

public class LeadExecutorUI extends UIController {
  protected RequestManagerLocalHome requestManagerHome;
  protected EmployeeManagerLocalHome employeeManagerHome;
  
  public LeadExecutorUI() {
    super();
  }
      
  public void init(ServletConfig config) throws ServletException {    
    super.init(config);
    try {
       
    requestManagerHome =
      Utils.getRequestManagerHomeInterface();
    
    employeeManagerHome =
       Utils.getEmployeeManagerHomeInterface();
    
    } catch (Exception e){
      handleException(e, "init");
    }
  }

  
  protected void prologue(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
      
      request.getSession().setAttribute("alias", "leadexecutorui");
      Object userId = Utils.getUserId(request);

      if (
         userId == null && !actionMapping.getActionName().equals("login")
      ) {         
         throw new LoginException("ErrorMessage.relogin");
      }

      String uri = request.getRequestURI();
      String query = request.getQueryString();

      if (query != null) {
         uri += "?" + query;
      }

      String uriEncoded = URLEncoder.encode(uri, "UTF-8");
      request.setAttribute("uri", uri);
      request.setAttribute("uriEncoded", uriEncoded);
      
//    messages list                    
      request.setAttribute(
        "messagesList", 
        new ArrayList<MessageBean>()
      );      
   }
  
  
  private void displayTasksList(
     HttpServletRequest request
  ) {     
     try {
      int userId = Utils.getUserId(request);
        
        if (request.getParameter("sidebartpage") != null) {
           request.getSession().setAttribute(
              "sidebartpage", 
              Utils.idVal(request.getParameter("sidebartpage"))
           ); 
        }        
        
        int page = (request.getSession().getAttribute("sidebartpage") == null) ? 
           0 : (Integer)request.getSession().getAttribute("sidebartpage");
        
        int itemsPerPage = 5; 
        
        IntWrapper records = new IntWrapper(0);         
        
        String order = request.getParameter("sidebarorder");
        String orderBy = request.getParameter("sidebarorderBy");
        
        order = (order == null) ? "DESC" : order;                
        orderBy = (orderBy == null) ? "N" : orderBy;         
        
        Collection<TaskBean> tasksList = null;
        
        TaskBean searchTaskTemplate = 
           (TaskBean)request.getSession().getAttribute("searchTaskTemplate");
        
        RequestManagerLocalObject requestManager = 
           requestManagerHome.create();                           
        
        
        if (searchTaskTemplate != null)
        tasksList = 
           requestManager.searchTasksByExecutor(
             searchTaskTemplate,
             orderBy, 
             order,
             page,
             itemsPerPage,
             records
           );         
        else
        tasksList = 
        requestManager.selectTasksByExecutor(
           userId, 
           order, 
           orderBy,
           page,
           itemsPerPage,
           records
        );
              
        request.setAttribute("tasksList", tasksList);
        
        Utils.pageNavigationToRequest(
           page,          
           records.getValue(), 
           "leadexecutorui?_action=dumb&sidebartpage=",
           request,
           "sidebarpaging",
           "sidebarcurrentpage"
        );
   } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
   } 
  }
  
  
  private void displayRequestsList(HttpServletRequest request) {
     try {         
        RequestManagerLocalObject requestManager = 
           requestManagerHome.create();                                 
        
        if (request.getParameter("sidebarrpage") != null) {
           request.getSession().setAttribute(
              "sidebarrpage", 
              Utils.idVal(request.getParameter("sidebarrpage"))
           ); 
        }                
        
        int page = (request.getSession().getAttribute("sidebarrpage") == null) ? 
           0 : (Integer)request.getSession().getAttribute("sidebarrpage");
        
        int itemsPerPage = 5;         
        
        IntWrapper records = new IntWrapper(0);         
        
        String order = request.getParameter("sidebarorder");
        String orderBy = request.getParameter("sidebarorderBy");
        
        order = (order == null) ? "DESC" : order;                
        orderBy = (orderBy == null) ? "N" : orderBy;                               
        
        Collection<RequestBean> requestsList = null;
        
        RequestBean searchRequestTemplate = 
           (RequestBean)request.getSession().getAttribute("searchRequestTemplate");
        
        if (searchRequestTemplate != null)
           requestsList = 
              requestManager.searchRequests(
                 searchRequestTemplate,
                 orderBy, 
                 order,
                 page,
                 itemsPerPage,
                 records
              );
        else
           requestsList = 
              requestManager.selectRequestsByLeadExecutor(
                Utils.getUserId(request),
                orderBy,
                order,
                "'2','3','4','5','6'",
                page,
                itemsPerPage,
                records
              );              
                 
        request.setAttribute("requestsList", requestsList);
        Utils.pageNavigationToRequest(
            page,          
            records.getValue(), 
            "leadexecutorui?_action=dumb&sidebarrpage=",
            request,
            "sidebarpaging",
            "sidebarcurrentpage"
         );
        
        requestManager.remove();                                    
     } catch (Exception e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
     }
  }

  
  
   private void displaySideBarList(HttpServletRequest request) {
      try {         
         Action action = Action.valueOf(
            (String)request.getSession().getAttribute("_sideBarListType")
         );        
         
         switch (action) {
            case displayTasksList:
            displayTasksList(request);                                               
            break;

            default:               
            displayRequestsList(request);                                              
         }
                                     
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }     
   }
   
   
   private void displayUserName(HttpServletRequest request) {
      try {
         int userId = Utils.getUserId(request);
         
         EmployeeManagerLocalObject employeeManager = 
            employeeManagerHome.create();
         
         EmployeeBean employeeBean = 
            employeeManager.selectEmployee(userId);
                  
         request.setAttribute("userName", employeeBean.getFormName());
         
         employeeManager.remove();
      } catch (Exception e) {
         // TODO Auto-generated catch block
         e.printStackTrace();
      }     
   }
  
  
   protected void epilogue(
      ActionMapping actionMapping,
      HttpServletRequest request,
      HttpServletResponse response
   ) throws IOException, ServletException {
     try {  
              
       this.displaySideBarList(request);
       this.displayUserName(request);
       
     } catch (Exception e) {
        handleException(e, "epilogue");
     }
   }
}